// simulator.js - 原生 ES 模块，浏览器直接 import
const WS_PORT = 8765;

// 简单的随机场景生成器
function makeFrame() {
  const depth   = 55 + Math.floor(Math.random() * 11);   // 55-65 mm
  const rate    = 110 + Math.floor(Math.random() * 11);  // 110-120 次/分
  const recoil  = 1;                                     // 已回弹
  const ventVol = 300 + Math.floor(Math.random() * 51); // 300-350 ml
  return depth, rate, recoil, ventVol;
}

// 引入你的冻结协议
import { buildFrame } from './frame.js';

// WebSocket 服务器（浏览器端）
let wsServer = null;
let frameNo = 0;

function startServer() {
  wsServer = new WebSocket(`ws://localhost:${WS_PORT}`);
  wsServer.binaryType = 'arraybuffer';
  wsServer.onopen = () => console.log('[SIM] WebSocket 已监听', WS_PORT);
  wsServer.onclose = () => console.log('[SIM] 断开');
}

// 每 30 ms 吐 20 字节帧
setInterval(() => {
  if (!wsServer || wsServer.readyState !== WebSocket.OPEN) return;
  frameNo++;
  const [depth, rate, recoil, ventVol] = makeFrame();
  const frame = buildFrame(
    [0x19, 0x08, 0x16],  // 模型
    frameNo,             // 按压次数
    depth, 5, rate, 60, recoil,
    0, ventVol, 1, 25, 350
  );
  wsServer.send(frame);
}, 30);